<template>
    <sig-main>
        <div class="p clearfix">
            <panel :header="true" title="Login" class="panel-primary">
                <login-form :submit="login" :registerUrl="{name: 'Register'}"></login-form>
            </panel>
        </div>
        <document-title :title="title"></document-title>
    </sig-main>
</template>

<style scoped="">
    .p {
        width: 400px;
        position: relative;
        z-index: 10;
    }
</style>

<script>
    /* eslint-disable no-undef,no-multi-spaces */
    import SigMain from './SigMain.vue';
    import LoginForm from '../common/user/LoginForm.vue';
    import Panel from 'vue-fiu-ui/src/main/js/components/panel/Panel.vue';
    import DocumentTitle from '../layout/Title.vue';

    export default {
        data () {
            return {
                title: 'Login'
            };
        },
        components: {
            DocumentTitle,
            Panel,
            LoginForm,
            SigMain
        },
        methods: {
            login (data) {
                axios.post('/oauth/token', this.getRequestData(data)).then((res) => {
                    this.setLoginData(res.data);
                    this.getUserInfo();
                });
            },
            getRequestData (data) {
                let params = {};
                params.grant_type = 'password';
                params.client_id = this.$key.CLIENT_ID;
                params.client_secret = this.$key.CLIENT_SECRET;
                params.username = data.email;
                params.password = data.password;
                return params;
            },
            setLoginData (data) {
                this.$storage.clear();
                this.$storage.set(this.$key.ACCESS_TOKEN, data.access_token);
                this.$storage.set(this.$key.REFRESH_TOKEN, data.refresh_token);
                this.$storage.set(this.$key.EXPIRES_IN,  (new Date().getTime() + (data.expires_in * 1000)));
            },
            getUserInfo () {
                axios.get('/user/info').then((res) => {
                    if (res.data.success === false) {
                        throw new Expression('not find user');
                    } else {
                        this.$storage.set(this.$key.USER_DATA, JSON.stringify(res.data.data));
                        this.$router.push({name: 'DashBoard'});
                    }
                });
            }
        },
        mounted () {
        }
    };
</script>
